﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.IO;
using System.Security.Principal;
using System.Drawing.Printing;
using System.Configuration;

namespace Check_Printing_Solution
{
    public partial class IntegratedForm : Form
    {
        PrintManager manager = new PrintManager();

        public IntegratedForm()
        {
            InitializeComponent();
        }

        public void RefreshManager()
        {
            manager = new PrintManager();
        }

        private void tsbAddCustomer_Click( object sender, EventArgs e )
        {
            ManageCustomers addcustomer = new ManageCustomers( Operations.Add );
            addcustomer.ShowDialog();
        }

        private void tsbUpdateCustomer_Click( object sender, EventArgs e )
        {
            ManageCustomers updatecustomer = new ManageCustomers( Operations.Update );
            updatecustomer.ShowDialog();
        }

        private void tsbAddBank_Click( object sender, EventArgs e )
        {
            ManageBank addbank = new ManageBank( Operations.Add );
            addbank.ShowDialog();
        }

        private void tsbUpdateBank_Click( object sender, EventArgs e )
        {
            ManageBank addbank = new ManageBank( Operations.Update );
            addbank.ShowDialog();
        }

        private void tsbExit_Click( object sender, EventArgs e )
        {
            this.Close();
        }

        private void IntegratedForm_Load( object sender, EventArgs e )
        {
            this.Text = "Cheque Printing Solution - Version: " + Application.ProductVersion.ToString();
            lblLoggedInUser.Text = "You are currently logged in as: " + WindowsIdentity.GetCurrent().Name.ToString();

            txtAccountNumber.AutoCompleteSource = AutoCompleteSource.CustomSource;
            AutoCompleteStringCollection lookupaccounts = new AutoCompleteStringCollection();
            List<string> accounts = manager.GetAllAccountNumbers();
            foreach ( string account in accounts )
            {
                lookupaccounts.Add( account );
            }
            txtAccountNumber.AutoCompleteCustomSource = lookupaccounts;

            txtBranchNumber.AutoCompleteSource = AutoCompleteSource.CustomSource;
            AutoCompleteStringCollection lookupprefix = new AutoCompleteStringCollection();
            List<string> prefixes = manager.GetAllBranchNumbers();
            foreach ( string prefix in prefixes )
            {
                lookupprefix.Add( prefix );
            }
            txtBranchNumber.AutoCompleteCustomSource = lookupprefix;

            cmbChequeFormat.DataSource = manager.GetAllChequeTypes();
            cmbChequeFormat.DisplayMember = "Name";
            cmbChequeFormat.ValueMember = "Id";
        }

        private void tsManageChequeTypes_Click( object sender, EventArgs e )
        {
            ManageChequeTypes managechequetypes = new ManageChequeTypes();
            managechequetypes.ShowDialog();
        }

        private void tsbConfig_Click( object sender, EventArgs e )
        {
            RefreshBankFields();
            RefreshCustomerFields();

            ConfigurationForm configurationform = new ConfigurationForm( this );
            configurationform.ShowDialog();
        }

        private void tsPrintFile_Click( object sender, EventArgs e )
        {
            PrintSelected printselected = new PrintSelected( this );
            printselected.ShowDialog();
        }

        private void tsUploadFile_Click( object sender, EventArgs e )
        {
            if ( openFileDialog2.ShowDialog() == System.Windows.Forms.DialogResult.OK )
            {
                File.Copy( openFileDialog2.FileName, ConfigurationManager.AppSettings[ "SavePath" ].ToString() + Guid.NewGuid().ToString() + ".XLS", true );
                MessageBox.Show( "File upload has been completed.", "File Upload", MessageBoxButtons.OK, MessageBoxIcon.Information );
            }
        }

        private void txtBranchNumber_Leave( object sender, EventArgs e )
        {
            RefreshBankFields();
            GetLastNumberPrinted();
        }

        private void txtAccountNumber_Leave( object sender, EventArgs e )
        {
            RefreshManager();
            RefreshCustomerFields();
            GetLastNumberPrinted();
        }

        private void RefreshBankFields()
        {
            if ( txtBranchNumber.Text.Trim() != string.Empty )
            {
                Bank bank = manager.GetBankByBankCode( txtBranchNumber.Text );
                if ( bank != null )
                {
                    lblBankname.Text = bank.Name;
                    lblBranchCode.Text = bank.BranchCode + "-" + bank.BranchPrefix;
                    lblBankAddress.Text = bank.BankAddress;
                    lblBank.Text = bank.BranchCode + "-" + bank.BranchPrefix;
                }
            }
        }

        private void RefreshCustomerFields()
        {
            if ( txtAccountNumber.Text.Trim() != string.Empty )
            {
                Customer customer = manager.GetCustomerByAccount( txtAccountNumber.Text );
                if ( customer != null )
                {
                    txtFirstName.Text = customer.FirstName;
                    txtLastName.Text = customer.LastName;
                    txtLine1.Text = customer.Line1;
                    txtLine2.Text = customer.Line2;
                    txtLine3.Text = customer.Line3;
                    txtLine4.Text = customer.Line4;
                    lblBank.Text = customer.Bank.BranchPrefix + "-" + customer.Bank.BranchCode;
                    txtComment.Text = customer.Ext;
                }
            }
        }

        private void tsPrintCheque_Click( object sender, EventArgs e )
        {
            RefreshBankFields();
            //RefreshCustomerFields();

            if ( cmbChequeFormat.SelectedValue != null )
            {
                bool isclean = true;
                Customer customer = manager.GetCustomerByAccount( txtAccountNumber.Text );

                if ( customer.FirstName != txtFirstName.Text )
                {
                    isclean = false;
                }
                else if ( customer.LastName != txtLastName.Text )
                {
                    isclean = false;
                }
                else if ( customer.Line1 != txtLine1.Text )
                {
                    isclean = false;
                }
                else if ( customer.Line2 != txtLine2.Text )
                {
                    isclean = false;
                }
                else if ( customer.Line3 != txtLine3.Text )
                {
                    isclean = false;
                }
                else if ( customer.Line4 != txtLine4.Text )
                {
                    isclean = false;
                }
                else if ( customer.ChequeNumber != txtAccountNumber.Text )
                {
                    isclean = false;
                }

                if ( !isclean )
                {
                    if ( MessageBox.Show( "The customer details have been changed. Would you like to update to the newer information?", "Update Customer", MessageBoxButtons.YesNo, MessageBoxIcon.Question ) == System.Windows.Forms.DialogResult.Yes )
                    {
                        customer.FirstName = txtFirstName.Text;
                        customer.LastName = txtLastName.Text;
                        customer.Line1 = txtLine1.Text;
                        customer.Line2 = txtLine2.Text;
                        customer.Line3 = txtLine3.Text;
                        customer.Line4 = txtLine4.Text;
                        customer.ChequeNumber = txtAccountNumber.Text;
                        manager.UpdateCustomer( customer );
                    }
                }

                Print( cmbChequeFormat.SelectedValue.ToString() );
            }
            else
            {
                MessageBox.Show( "No Cheque Template has been selected. Please select a suitable Cheque Template before clicking Print.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error );
            }
        }

        public void Print( string chequeformatstyleid )
        {
            PrintChequeEngine pe = new PrintChequeEngine();

            if ( printDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK )
            {
                try
                {
                    pe.InitiatePrint( printDialog1.PrinterSettings.PrinterName,
                        manager.GetCustomerByAccount( txtAccountNumber.Text.Trim() ),
                        manager.GetBankByBankCode( txtBranchNumber.Text.Trim() ),
                        cmbChequeFormat.Text,
                        Convert.ToInt32( txtTotalCheques.Text.Trim() ),
                        txtComment.Text.Trim(),
                        txtNextChequeNumber.Text.Trim(), chequeformatstyleid, chkIgnoreSeq.Checked, txtNumBooks.Text,
                        Convert.ToInt32( txtOffSetX.Text ), Convert.ToInt32( txtOffSetY.Text ), chkIsReprint.Checked );

                    UpdatePrintStatus( "Completed", printDialog1.PrinterSettings.PrinterName, txtTotalCheques.Text, DateTime.Now.ToString() );
                }
                catch ( Exception ex )
                {
                    manager.LogApplicationEvent( new ApplicationLog()
                    {
                        EventTime = DateTime.Now,
                        EventUser = WindowsIdentity.GetCurrent().Name.ToString(),
                        Event = ex.ToString()
                    } );
                    MessageBox.Show( "Please ensure that all fields are filled out and all cheques are properly set up.", "Print Error.", MessageBoxButtons.OK, MessageBoxIcon.Error );
                }
            }
        }

        private void UpdatePrintStatus( string status, string printer, string pages, string time )
        {
            lblStatus.Text = status;
            lblPrinter.Text = printer;
            lblPages.Text = pages;
            lblTime.Text = time;
        }

        private void btnRefresh_Click( object sender, EventArgs e )
        {
            cmbChequeFormat.DataSource = manager.GetAllChequeTypes();
            cmbChequeFormat.DisplayMember = "Name";
            cmbChequeFormat.ValueMember = "Id";
        }

        private void tsPrintSelected_Click( object sender, EventArgs e )
        {
            PrintSelected printselected = new PrintSelected( this );
            printselected.ShowDialog();
        }

        private void cmbChequeFormat_SelectedIndexChanged( object sender, EventArgs e )
        {
            TemplateLayout layout = manager.GetTemplateLayout( cmbChequeFormat.SelectedValue.ToString() );
            lblType.Text = cmbChequeFormat.Text;

            if ( layout != null )
            {
                //chkSkip.Checked = layout.Skip;
                lblSeqNumber.Text = layout.DepositSlips;
            }

            GetLastNumberPrinted();
        }

        private void tsPrintCover_Click( object sender, EventArgs e )
        {
            RefreshBankFields();
            RefreshCustomerFields();

            if ( cmbChequeFormat.SelectedValue != null )
            {
                PrintCoverEngine pe = new PrintCoverEngine();

                if ( printDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK )
                {
                    Customer customer = manager.GetCustomerByAccount( txtAccountNumber.Text );

                    customer.FirstName = txtFirstName.Text;
                    customer.LastName = txtLastName.Text;
                    customer.Line1 = txtLine1.Text;
                    customer.Line2 = txtLine2.Text;
                    customer.Line3 = txtLine3.Text;
                    customer.Line4 = txtLine4.Text;
                    customer.ChequeNumber = txtAccountNumber.Text;
                    manager.UpdateCustomer( customer );
                    try
                    {
                        pe.InitiatePrint( printDialog1.PrinterSettings.PrinterName,
                            manager.GetCustomerByAccount( txtAccountNumber.Text.Trim() ),
                            manager.GetBankByBankCode( txtBranchNumber.Text.Trim() ),
                            cmbChequeFormat.Text,
                            Convert.ToInt32( txtTotalCheques.Text.Trim() ),
                            txtComment.Text.Trim(),
                            txtNextChequeNumber.Text.Trim(), cmbChequeFormat.SelectedValue.ToString(),
                            Convert.ToInt32( txtOffSetX.Text ), Convert.ToInt32( txtOffSetY.Text ) );

                        UpdatePrintStatus( "Completed", printDialog1.PrinterSettings.PrinterName, txtTotalCheques.Text, DateTime.Now.ToString() );
                    }
                    catch ( Exception ex )
                    {
                        MessageBox.Show( "Please ensure that all fields are filled out and all cheques are properly set up.", "Print Error.", MessageBoxButtons.OK, MessageBoxIcon.Error );
                    }
                }
            }
        }

        private void tsPrintLabels_Click( object sender, EventArgs e )
        {
            if ( openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK )
            {
                string filename = openFileDialog1.FileName;
                string connectionString = string.Format( "Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=Excel 8.0;", filename );

                //Customer information
                OleDbDataAdapter adpater = new OleDbDataAdapter( "SELECT * FROM [Sheet1$]", connectionString );
                DataSet ds = new DataSet();
                adpater.Fill( ds, "Customers" );

                OleDbDataAdapter adpater2 = new OleDbDataAdapter( "SELECT * FROM [DATA Source$]", connectionString );
                adpater2.Fill( ds, "Banks" );

                ds = manager.CleanCustomers( ds );
                ds = manager.CleanBanks( ds );

                //Call class to start printing
                PrintLabelEngine pe = new PrintLabelEngine();
                if ( printDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK )
                {
                    try
                    {
                        pe.InitiatePrint( ds, printDialog1.PrinterSettings.PrinterName );
                        UpdatePrintStatus( "Completed", printDialog1.PrinterSettings.PrinterName, ds.Tables[ "Customers" ].Rows.Count.ToString(), DateTime.Now.ToString() );
                    }
                    catch ( Exception ex )
                    {
                        MessageBox.Show( "There is a formatting issue with the XLS file. Please review.", "Input File Error.", MessageBoxButtons.OK, MessageBoxIcon.Error );
                    }
                }
            }
        }

        private void tsLogs_Click( object sender, EventArgs e )
        {
            Log log = new Log();
            log.ShowDialog();
        }

        public void SetLogs( List<string> logs )
        {
            foreach ( string logrecord in logs )
            {
                //txtComment.Text += logrecord + "\r\n" + "\r\n";
            }
        }

        private void txtComment_TextChanged( object sender, EventArgs e )
        {

        }

        private void btnSaveNotes_Click( object sender, EventArgs e )
        {
            if ( txtAccountNumber.Text == string.Empty )
            {
                MessageBox.Show( "Please select a customer before saving notes.", "Save Error.", MessageBoxButtons.OK, MessageBoxIcon.Error );
            }
            else
            {
                manager.SaveNotes( txtAccountNumber.Text, txtComment.Text );
            }
        }

        public void GetLastNumberPrinted()
        {
            if ( txtAccountNumber.Text != string.Empty && txtBranchNumber.Text != string.Empty )
            {
                int lastnumber = manager.GetLastChequeNumber( txtAccountNumber.Text, txtBranchNumber.Text, cmbChequeFormat.Text );
                txtNextChequeNumber.Text = ( lastnumber ).ToString();

                JobLog joblog = manager.GetLastLogEntry( txtAccountNumber.Text, txtBranchNumber.Text, cmbChequeFormat.Text );
                try
                {
                    if ( joblog != null )
                    {
                        if ( joblog.DatePrinted != null )
                        {
                            lblLastTrans.Text = joblog.DatePrinted.ToShortDateString();
                        }
                        else
                        {
                            lblLastTrans.Text = "N/A";
                        }
                    }
                }
                catch
                {
                    lblLastTrans.Text = "N/A";
                }
            }
        }
    }
}
